import React, { PureComponent, Fragment } from 'react';
import moment from 'moment';
import { connect } from 'dva';
import {
  Button,
  Tag,
  Modal,
  Form,
  message,
  Table,
  Radio,
  Input,
  Icon,
  Drawer,
  Row,
  Col,
  Switch,
  Progress, DatePicker, Select,
} from 'antd';
import MyPagination from '@/components/MyPagination';
import Loading from '@/components/Loading';

import find from 'lodash/find';
import debounce from 'lodash/debounce';
import { ellipsis, afterCloseModal, DescriptionItem } from '@/utils/utils';
import { routerRedux } from 'dva/router';
import BuildModalTitle from '@/components/BuildModalTitle';
import ReactDataGrid from 'react-data-grid';
import AddOrEditUser from './addOrEditUser';
import imgFile from './../../images/image.png'
import ReactEcharts from 'echarts-for-react';
const FormItem = Form.Item;
const { confirm } = Modal;
const { Option } = Select;

const RadioButton = Radio.Button;

const RadioGroup = Radio.Group;

@connect(({ inspection_statistics, loading, global }) => ({
  inspection_statistics,
  global,
  loading: loading.models.inspection_statistics,
}))
@Form.create()
class BasicList extends PureComponent {
  constructor(props) {
    super(props);
    this.permissions = JSON.parse(sessionStorage.getItem('permissions'));
    this.state = {
      showAddBtn: find(this.permissions, { name: 'device_add_and_edit' }),
      showdelBtn: find(this.permissions, { name: 'device_delete' }),
      showPasswordBtn: find(this.permissions, { name: 'user_default_password_edit' }),
      user_password_reset: find(this.permissions, { name: 'user_password_reset' }),
      visible: false,
      done: false,
      page: 1,
      per_page: 30,
      username: '',
      editRecord: {},
      selectedRowKeys: [],
    };
  }


  componentDidMount() {

    const { dispatch } = this.props;
    const {
      inspection_statistics: { pageLoaded, scrollData },
    } = this.props;
    console.log('pageLoaded', pageLoaded);
    const table = document.querySelector('.react-grid-Canvas');
    if (pageLoaded) {
      setTimeout(() => {
        table.scrollTop = scrollData.y;
        table.scrollLeft = scrollData.x;
      }, 0);

    } else {
      const {
        inspection_statistics: { searchParams },
      } = this.props;
      console.log('searchParams', searchParams);
      dispatch({
        type: 'inspection_statistics/fetch',
        payload: searchParams,
        callback: () => {
          const { dispatch } = this.props;
          dispatch({
            type: 'inspection_statistics/changeLoaded',
          });
          dispatch({
            type: 'inspection_statistics/changeTableY',
          });
        },
      });

    }
    window.addEventListener('resize', this.resize);
    table.addEventListener('scroll', debounce(this.scroll, 150));
  }

  scroll = (e) => {
    console.log('scroll');
    const { dispatch } = this.props;
    dispatch({
      type: 'inspection_statistics/changeScroll',
      payload: {
        x: e.target.scrollLeft,
        y: e.target.scrollTop,
      },
    });
  };

  resize = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'inspection_statistics/changeTableY',
    });
  };
  findChildFunc = (cb) => {
    this.file = cb;
  };

  componentWillUnmount() {
    console.log('componentWillUnmount');
    window.removeEventListener('resize', this.resize);
    const table = document.querySelector('.react-grid-Canvas');
    table.removeEventListener('scroll', debounce(this.scroll, 300));
  }

  handleSearch = (values, cb) => {
    console.log('handleSearch', values);
    const that = this;
    const { dispatch } = this.props;
    dispatch({
      type: 'inspection_statistics/fetch',
      payload: {
        ...values,
      },
      callback() {
        console.log('handleSearch callback');
        if (cb) cb();
      },
    });
  };

  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
      inspection_statistics: { searchParams },
    } = this.props;
    return (
      <Form layout="inline" className="search-form">
        <FormItem>

          <Button
            type="primary"
            icon='search'
            onClick={() => {
              const { form } = this.props;
              form.validateFields((err, fieldsValue) => {
                if (err) return;

                this.handleSearch({
                  page: 1,
                  per_page: searchParams.per_page,
                  ...fieldsValue,
                });

              });
            }}
          >
            刷新
          </Button>
        </FormItem>

      </Form>
    );
  }

  handleAdd = () => {
    const formValues = this.AddForm.props.form.getFieldsValue();
    console.log('formValues', formValues);
    const that = this;
    this.props.dispatch({
      type: 'inspection_statistics/add',
      payload: {
        ...formValues,
      },
      callback() {
        message.success('添加员工成功');
        that.setState({
          addModal: false,
        });
        const {
          inspection_statistics: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };

  handleFormReset = () => {
    const { form } = this.props;
    form.resetFields();
    this.handleSearch({
      username: '',
      page: 1,
      per_page: 30,
    });
  };

  handleEdit = () => {
    const formValues = this.EditForm.props.form.getFieldsValue();
    console.log('formValues', formValues);
    const that = this;
    this.props.dispatch({
      type: `inspection_statistics/edit`,
      payload: {
        ...formValues,
        id: this.state.editRecord.id,
      },
      callback() {
        message.success('修改员工成功');
        that.setState({
          editModal: false,
        });
        const {
          inspection_statistics: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };
  handleDelete = id => {
    const that = this;
    const { dispatch } = this.props;
    dispatch({
      type: `inspection_statistics/remove`,
      payload: { id },
      callback: () => {
        message.success('删除员工成功');
        const {
          inspection_statistics: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };
  getOption=(value)=>{
    let colors = ['#1ac47c', '#ffb661', '#ff625e'];

    let  option = {
      series: [{
        // name: 'CPU使用率',
        type: 'gauge',
        // center: ["50%", "50%"], // 仪表位置
        // radius: "75%", //仪表大小
        min: 0,
        max: 100,
        axisLine: {
          // 仪表盘
          lineStyle: {
            width: 4,
            color: [
              [0.6, colors[2]],
              [0.8, colors[1]],
              [1, colors[0]]
            ]
          }
        },
        splitLine: {
          // 分隔线样式
          length: "6%"
        },
        axisTick: {
          // 刻度样式
          show: false
        },
        axisLabel: {
          // 刻度标签
          fontSize: 10,
          distance: 5
        },
        pointer: {
          // 仪表盘指针
          width: 5,
          length: "65%"
        },
        markPoint: {
          // 仪表盘指针圆
          animation: false,
          silent: true,
          data: [{
            x: '50%',
            y: '50%',
            symbol: 'circle',
            symbolSize: 20,
            // itemStyle: {
            //     color: '#1890ff',
            // },
          }, {
            x: '50%',
            y: '50%',
            symbol: 'circle',
            symbolSize: 10,
            itemStyle: {
              color: '#fff'
            },
          }]
        },
        detail: {
          // 仪表盘 显示数据
          formatter: '{value}%',
          fontSize: 14,
          fontWeight: 'bold'

        },
        data: [{
          value: Number(value),
          // name: ""
        }],
      }]
    };
    return option
  }
  render() {
    const that = this;
    let {
      inspection_statistics: { data, loading, tableY, meta, searchParams, selectedRowKeys },
      global: { gridTableW },
    } = this.props;

    const defaultColumnProperties = {
      resizable: true,
    };
    const columns = [
      {
        name: '序号',
        width: 50,

        key: '_index',
        frozen: true,
        formatter: (event) => {
          return <p className={'index'}>{(event.value + 1)}</p>;
        },
      },
      {
        name: '巡检员',
        width: 100,
        key: 'inspector_name',
      },
      {
        name: '已受理工单数量',
        width: 140,
        key: 'confirm_count',
      },
      {
        name: '完成工单数量',
        width: 140,
        key: 'complete_count',
      },
      {
        name: '完成率',
        width: 160,
        key: 'status12213',
        formatter: (event) => {
          return <div style={{width:'160px',height:'160px',marginLeft:'-8px'}}>
          <ReactEcharts
            option={this.getOption((event.row.confirm_count/event.row.confirm_count) * 100)}
            style={{ height: '160px', width: '160px' }}
            theme='my_theme'
            //onChartReady={this.onChartReadyCallback}
            //onEvents={EventsDict}
            /></div>;
        },
      },

    ].map(c => ({ ...defaultColumnProperties, ...c }));

    let totalWidth = 0;
    for (let i = 0; i < columns.length; i++) {
      totalWidth += columns[i].width;
    }
    if (totalWidth < gridTableW) {
      columns[columns.length - 1].width = columns[columns.length - 1].width + gridTableW - totalWidth;
    }
    data=data.slice(0,2)

    return <div className="custom-card">
      <div className="table-title"><span className={'title-item'}>巡检员统计</span>
      </div>
      <div className="table-page">
        <div className="table-condition">{this.renderSimpleForm()}</div>
        <div className={'table-data-content'}>
          <ReactDataGrid
            columns={columns}
            rowGetter={i => {
              return { ...data[i], _index: i };
            }}
            rowsCount={data.length}
            minHeight={tableY}
            headerRowHeight={35}
            rowHeight={160}
            rowSelection={{
              showCheckbox: false,
              enableShiftSelect: true,
              selectBy: {
                indexes: selectedRowKeys,
              },
            }}
            onRowClick={
              (row) => {
                this.props.dispatch({
                  type: 'inspection_statistics/changeSelectRow',
                  payload: [row],
                });
              }
            }

          />
          {
            loading && <Loading/>
          }
        </div>


      </div>
      <Modal
        title={<BuildModalTitle visible={this.state.addModal} modalClass="addModal" title="发布工单"/>}
        className="addModal"
        visible={this.state.addModal}
        centered
        onCancel={() => {
          this.setState({ addModal: false });
        }}
        onOk={this.handleAdd}
      >
        <AddOrEditUser
          wrappedComponentRef={(inst) => this.AddUser = inst}/>

      </Modal>
    </div>;
  }
}

export default BasicList;
